const connection = require('../app/database')
const schedule = require('node-schedule')
const dayjs = require('dayjs')
// 每分钟检查一次
const startTimeJob = schedule.scheduleJob('*/1 * * * *', async function () {
	const dayjs = require('dayjs')
	const formattedTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
	// 构建一个 SQL 查询，假设你的表名为 `events`，时间字段为 `event_time`，状态字段为 `status`
	const startQuery = `
    UPDATE events 
    SET status = 'ongoing' 
    WHERE start_date <= ? AND end_date >= ? AND status = 'approved';
  `
	const endQuery = `
    UPDATE events 
    SET status = 'finished' 
    WHERE end_date <= ? AND status = 'ongoing';
  `

	try {
		// 执行查询并传递当前时间
		const [results] = await connection.execute(startQuery, [
			formattedTime,
			formattedTime
		])
		const [result2] = await connection.execute(endQuery, [formattedTime])

		// 查看是否有行被更新
		if (results.affectedRows > 0) {
			console.log(`${results.affectedRows} events updated to 'ongoing' status.`)
		}
		if (result2.affectedRows > 0) {
			console.log(
				`${results.affectedRows} events updated to 'finished' status.`
			)
		}
	} catch (error) {
		console.error('Error updating events:', error)
	}
})
